//
//  FamilyAddFormCell.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/24.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

enum FamilyAddFormCellType: Int {
    case name     = 0
    case idCard
    case area
    case address
    case phone
    case relation
    case commonly
    case sure // 确定
    
    var placeholder: String {
        switch self {
        case .name: return "请输入姓名"
        case .idCard: return "请输入身份证号码"
        case .area: return "请选择省市区"
        case .address: return "请输入详细地址"
        case .phone: return "请输入手机号"
        case .relation: return "选填"
        default: return ""
        }
    }
}

protocol FamilyAddFormCellDelegate: NSObjectProtocol {
    func familyFormCell(_ cell: FamilyAddFormCell, didEndEditing vm: FamilyAddViewModel)
    func familyFormCell(_ cell: FamilyAddFormCell, didClickedCommonly vm: FamilyAddViewModel)
    func familyFormCell(didClickedSure cell: FamilyAddFormCell)
}

class FamilyAddFormCell: UITableViewCell {
    
    weak var delegate: FamilyAddFormCellDelegate?
    private var vm = FamilyAddViewModel(model: FamilyAddModel())
    private var cellType: FamilyAddFormCellType = .name {
        didSet {
            initUI(with: cellType)
        }
    }
    private var addType: FamilyAddType = .add {
        didSet {
            if addType == .add {
                self.isUserInteractionEnabled = true
                sureBtn.setBackgroundImage(UIImage(color: .mainColor), for: .normal)
                sureBtn.setBackgroundImage(UIImage(color: .mainLight), for: .highlighted)
                sureBtn.setTitle("确 定", for: .normal)
                sureBtn.setTitleColor(.white, for: .normal)
                sureBtn.layer.cornerRadius = sureBtn.height * 0.5
                sureBtn.layer.masksToBounds = true
            } else {
                self.isUserInteractionEnabled = cellType == .sure
                sureBtn.setBackgroundImage(UIImage(color: .white), for: .normal)
                sureBtn.setBackgroundImage(UIImage(color: .mainLight), for: .highlighted)
                sureBtn.setTitle("删 除", for: .normal)
                sureBtn.setTitleColor(.warning, for: .normal)
                sureBtn.layer.cornerRadius = sureBtn.height * 0.5
                sureBtn.layer.borderWidth = 1.0
                sureBtn.layer.borderColor = UIColor(hex: "#ECECEC").cgColor
                sureBtn.layer.masksToBounds = true
            }
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        selectionStyle = .none
    }

    func configure(with vm: FamilyAddViewModel, cellType: FamilyAddFormCellType, addType: FamilyAddType) {
        self.vm = vm
        self.cellType = cellType
        self.addType = addType
        
        switch cellType {
        case .name:
            textField.text = vm.name
        case .idCard:
            textField.text = vm.idcard
        case .phone:
            if self.addType == .add {
                textField.text = vm.phone.decryptWithAES()
            } else {
                textField.text = vm.phone
            }
        case .area:
            textField.text = vm.area
        case .address:
            textField.text = vm.addr
        case .commonly:
            commonlyBtn.isSelected = vm.isCommonly
        case .relation:
            textField.text = vm.relationName
        default: break
        }
    }
    
    @IBOutlet private weak var titleLabel: UILabel!
    @IBOutlet private weak var textField: UITextField! {
        didSet {
            textField.delegate = self
        }
    }
    @IBOutlet private weak var arrowView: UIImageView!
    @IBOutlet private weak var commonlyBtn: UIButton!
    @IBOutlet private weak var splitLine: UIView!
    @IBOutlet private weak var sureBtn: UIButton!
    
    @IBAction private func commonly(_ sender: UIButton) {
        textField.resignFirstResponder()
        sender.isSelected.toggle()
        vm.isDefault = sender.isSelected ? 1 : 0
        delegate?.familyFormCell(self, didClickedCommonly: vm)
    }
    
    @IBAction private func sure(_ sender: UIButton) {
        delegate?.familyFormCell(didClickedSure: self)
    }
}

extension FamilyAddFormCell {
    private func initUI(with cellType: FamilyAddFormCellType) {
        titleLabel.text = vm.titles[cellType.rawValue]
        textField.placeholder = cellType.placeholder
        switch cellType {
        case .area:
            setupAreaCell()
        case .phone:
            textField.keyboardType = .phonePad
        case .commonly:
            setupCommonlyCell()
        case .sure:
            setupSureCell()
        case .relation:
            setupAreaCell()
        default: break
        }
    }
    
    private func setupAreaCell() {
        arrowView.isHidden  = false
        textField.isEnabled = false
    }
    
    private func setupCommonlyCell() {
        textField.isHidden   = true
        commonlyBtn.isHidden = false
    }
    
    private func setupSureCell() {
        titleLabel.isHidden = true
        textField.isHidden  = true
        splitLine.isHidden  = true
        sureBtn.isHidden    = false
    }
}

extension FamilyAddFormCell: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        switch cellType {
        case .name: vm.name = textField.text!
        case .idCard: vm.idcard = textField.text!
        case .phone: vm.phone = textField.text!.encryptWithAES()
        case .address: vm.addr = textField.text!
        default: break
        }
        
        delegate?.familyFormCell(self, didEndEditing: vm)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if cellType == .idCard {
            let totalLength = (textField.text?.lengthOfBytes(using: .utf8))! - range.length + string.lengthOfBytes(using: .utf8)
            if totalLength > 18 { return false }
            let lengthOfStr = string.lengthOfBytes(using: .utf8)
            for index in 0..<lengthOfStr {
                let chara = (string as NSString).character(at: index)
                // 48-57;{0,9};65-90;{A..Z};97-122:{a..z}
                if chara < 48 { return false }
                if totalLength < 18 && chara > 57 {
                    return false
                }
                if totalLength == 18 &&
                    ((chara > 57 && chara < 65) || (chara > 90 && chara < 97) || chara > 122) {
                    return false
                }
            }
            return true
        } else if cellType == .phone {
            let totalLength = (textField.text?.lengthOfBytes(using: .utf8))! - range.length + string.lengthOfBytes(using: .utf8)
            if totalLength > 11 { return false }
            let lengthOfStr = string.lengthOfBytes(using: .utf8)
            for index in 0..<lengthOfStr {
                let chara = (string as NSString).character(at: index)
                // 48-57;{0,9};65-90;{A..Z};97-122:{a..z}
                if chara < 48 || chara > 57 { return false }
            }
            return true
        }
        return true
    }
}
